
export class promiseQue {
    taskList: (() => Promise<any>)[] = [];
    count: number = 0;
    currentTaskCount = 0;
    constructor(options: {
        count: number;
    }) {
        this.count = options.count;
    }
    addTask(task: () => Promise<any>) {
        if (!this.taskList.length) {
            Promise.resolve().then(() => {
                this.excuteList()
            })
        }
        if (Array.isArray(task)) {
            this.taskList = this.taskList.concat(task);
        } else {
            this.taskList.push(task);
        }
    }
    excuteList() {
        if (!this.taskList.length) {
            return;
        }
        if (this.taskList.length < this.count) {
            this.taskList.forEach(p => p().then(this.callNext));
        } else {
            const shiftArr = this.taskList.slice(0, this.count);
            this.taskList = this.taskList.slice(this.count);
            shiftArr.forEach(p => {
                p().then(this.callNext)
            })
        }
    }

    callNext = (data: any) => {
        console.log(data);
        if (this.taskList.length > 0 && this.currentTaskCount < this.count) {
            const shift = this.taskList.shift();
            shift && shift().then(this.callNext);
        }
    }
}


const que = new promiseQue({count: 3});
const testArr = [1,2,3,4,5,6,7].map(value => {
    return () => {
        return new Promise((resolve, reject) => {
            setTimeout(() => {
                resolve(value);
            }, value * 1000)
        })
    }
});
testArr.forEach(task => que.addTask(task))
